package cn.nihao365.crm.controller;

import cn.nihao365.common.config.SiteConfig;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.URLDecoder;
import java.util.Properties;

/**
 * @author zhu hui (zhuhui@nihao365.cn)
 * @version 1.0
 * @date 2021-11-15 22:37:37
 */
@RestController
@RefreshScope
public class SiteConfigController{

    @Autowired
    private ContextRefresher contextRefresher;

    @Autowired
    private SiteConfig siteConfig;

    @GetMapping("/site/config")
    public String getTitle() {
        // 解决中文乱码的问题
        System.out.println(siteConfig.toString());
        return siteConfig.getSysName();
    }

    @PostMapping("/site/config/refresh")
    public String refresh(@RequestBody SiteConfig siteConfig){
        try {
            String name = "config/site.properties";
            String filePath = PropertiesUtil.class.getClassLoader().getResource(name).getFile();
            filePath = URLDecoder.decode(filePath, "utf-8");
            Properties props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(name));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
            props.setProperty("site.sysName", siteConfig.getSysName());
            props.store(bw, "system config file");
            // TODO: 2021/11/18 同时要写入数据库
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        new Thread(() -> contextRefresher.refresh()).start();
        return "success";
    }

}
